# -*- coding: utf-8 -*-
from suds.client import Client
from suds.xsd.doctor import ImportDoctor, Import
import xmltodict
import time 

class APIHis(object):
    """
    医院侧获取厦门智业院内HIP系统数据
    webService客户端
    """

    __instance = None

    def __init__(self):

        self.imp = Import('http://www.w3.org/2001/XMLSchema', location='http://www.w3.org/2001/XMLSchema.xsd')
        self.imp.filter.add('http://WebXml.com.cn/')
        self.doctor = ImportDoctor(self.imp)
        self.url = 'http://285s704m25.qicp.vip/Dq-service/DqEntranceWs?wsdl'
        self.client = Client(self.url, doctor=self.doctor)

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance 

    def send_time(self):
        return time.strftime("%Y-%M-%d %H:%M:%S",time.localtime())
    
    def msg_no(self):
        return time.strftime("%Y%M%d%H%M%S",time.localtime())+'000'

    def xml_to_dict(self,xml):
        if isinstance(xml, str):
            if '<?xml ' not in xml:
                if '<root>' in xml:
                    xml = f'<?xml version="1.0" encoding="UTF-8" ?>{xml}'
                else:
                    return xml
            dic = xmltodict.parse(xml)
        elif isinstance(xml, dict):
            dic = xml
        else:
            return xml
    
        new_dic = {}
        for key, value in dic.items():
            value = self.xml_to_dict(value)
            new_dic[key] = value
        return new_dic

    def get_pacs_web_report(self,idCardType=None,idNo=None,registerDate=None,cureDept=None):
        """获取挂号列表"""
        """OrderedDict([('idCardType', '01'), ('idNo', '652927199105014728'), 
            ('cardNo', '652927199105014728'), ('nullahNumber', '25537'),
             ('name', '热比牙木·吐拉克'), ('sex', '2'),
              ('age', '31'), ('nation', '维吾尔族'),
               ('address', '新疆乌什县亚曼苏柯尔克孜民族乡阿依丁村2组239号'),
                ('aboType', None), ('rhType', None), ('state', '1001'),
                 ('registerDate', '2022'), ('cureDept', '307')])"""
        if not idCardType:
            idCardType=''
        cureDept_=''
        queryType=''
        if not idNo:
            idNo=''   
            cureDept_="305','311" 
            
        else:
            queryType=1000    
            if idCardType:
               idCardType='01' 
        if not registerDate:
            registerDate=''
        nullahNumber=cureDept
        if not cureDept:
            nullahNumber=""          
        msgHeader = '''
                    <?xml version="1.0" encoding="utf-8"?> 
                    <root> 
                    <serverName>GetOutpatientPatient</serverName> 
                    <format>XML</format> 
                    <callOperator>FYBT</callOperator> 
                    <certificate>sh4LPXxWKU8osDGF/c9kJMJ1k8gu6Qp+6IIjo745NDvQhQXzOYug4w==</certificate> 
                    <msgNo>{}</msgNo>
                    <sendTime>{}</sendTime>
                    <sendCount>0</sendCount>
                    </root>
                    '''.format(self.msg_no(),self.send_time())
        msgBody = '''
                    <?xml version="1.0" encoding="utf-8"?>
                    <root>
                       <queryType>{}</queryType>
                       <idCardType>{}</idCardType>
                       <idNo>{}</idNo>
                       <nullahNumber>{}</nullahNumber>
                       <registerDate>{}</registerDate>
                       <cureDept>{}</cureDept>
                    </root>
                  '''.format(queryType,idCardType,idNo,nullahNumber,registerDate,cureDept_)
        print (msgBody)
        result = []
        try:          
            result = self.client.service.CallInterface(msgHeader, msgBody)
            result = self.xml_to_dict(result)
            result = result['root']['returnContents']['returnContent']
        except Exception as e:
            print (e)
            pass #解析超时    
        return result

    def get_zybasicInfo(self,status):
        """未出院患者信息及已出院患者信息"""
        if not status:
            status = ''
        msgHeader = '''
                    <?xml version="1.0" encoding="utf-8"?> 
                    <root> 
                    <serverName>ZybasicInfo</serverName> 
                    <format>XML</format> 
                    <callOperator>FYBT</callOperator> 
                    <certificate>sh4LPXxWKU8osDGF/c9kJMJ1k8gu6Qp+6IIjo745NDvQhQXzOYug4w==</certificate> 
                    <msgNo>{}</msgNo>
                    <sendTime>{}</sendTime>
                    <sendCount>0</sendCount>
                    </root>
                    '''.format(self.msg_no(),self.send_time())
        msgBody = '''
                    <?xml version="1.0" encoding="utf-8"?> 
                    <root> 
                    <wardNo></wardNo> 
                    <inDept>411','413</inDept> 
                    <admissinDate></admissinDate> 
                    <sickState>{}</sickState> 
                    </root>
                  '''.format(status) #
        result = []
        try:          
            result = self.client.service.CallInterface(msgHeader, msgBody)
            result = self.xml_to_dict(result)
            print (result)
            result = result['root']['returnContents']['returnContent']
        except:
            pass #解析超时    
        return result    

if __name__ == '__main__':
    api_his=APIHis()
    t=api_his.get_zybasicInfo(1)
    print (t)